package model

import (
	"encoding/json"
	"fmt"
	"github.com/gogf/gf/v2/util/gconv"
	"log"
	"time"
)

const (
	PlainRes    = 5000
	UserInfoRes = 5001

	//这两个并发存在
	ChatRes      = 5010
	ChatOnlineIf = 5011
)

//服务端返回的消息

type IResMessage interface {
	Typeis() int32
	ResMsgis() *ResMessage

	Package() []byte
}

type ResMessage struct {
	Type int32
	Data interface{}
}

////ResChatMessage 从服务端返回的Chat消息，被封装在
type ResChatMessage struct {
	Time        time.Time
	MessageFrom string
	MessageTo   string
	Data        string
}

type ResPlainMessage struct {
	Status bool
	Data   interface{}
}

type ResUserInfoMessage struct {
	UserInfo *User
}

func (r *ResUserInfoMessage) Typeis() int32 {
	return UserInfoRes
}

func (r *ResUserInfoMessage) ResMsgis() *ResMessage {
	return &ResMessage{
		Type: r.Typeis(),
		Data: r,
	}
}

func (r *ResUserInfoMessage) Package() []byte {
	marshal, err := json.Marshal(r.ResMsgis())
	fmt.Println("打包后的信息是", string(marshal))
	if err != nil {
		panic(err)
	}
	return marshal
}

//ResMessage 从服务端一般性质的返回消息

func (rs *ResPlainMessage) DataString() {

}

func (r *ResPlainMessage) Typeis() int32 {
	return PlainRes
}

func (r *ResPlainMessage) ResMsgis() *ResMessage {
	return &ResMessage{
		Type: r.Typeis(),
		Data: r,
	}
}

func (r *ResPlainMessage) Package() []byte {
	marshal, err := json.Marshal(r.ResMsgis())
	if err != nil {
		panic(err)
	}
	return marshal
}

func (r *ResChatMessage) Typeis() int32 {
	return ChatRes
}

func (r *ResChatMessage) ResMsgis() *ResMessage {
	return &ResMessage{
		Type: r.Typeis(),
		Data: r,
	}
}

func (r *ResChatMessage) Package() []byte {
	marshal, err := json.Marshal(r.ResMsgis())
	if err != nil {
		panic(err)
	}
	return marshal
}

func (r *ResChatMessage) Bytes() []byte {
	marshal, err := json.Marshal(r)
	if err != nil {
		panic(err)
	}
	return marshal
}

func NewTrueRes(in interface{}) *ResPlainMessage {
	r := new(ResPlainMessage)
	r.Status = true
	r.Data = in
	return r
}

func NewTrueResWithPong() *ResPlainMessage {
	r := new(ResPlainMessage)
	r.Status = true
	r.Data = "pong"
	return r
}

func NewFalseRes(in interface{}) *ResPlainMessage {
	r := new(ResPlainMessage)
	r.Status = false
	r.Data = in
	return r
}

func UnPackageToResMessage(b []byte) IResMessage {
	fmt.Println("解包前的数据是", string(b))
	msg := new(ResMessage)
	err := json.Unmarshal(b, msg)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("解包后的数据是", msg)
	switch msg.Type {
	case PlainRes:
		r := new(ResPlainMessage)
		gconv.Struct(msg.Data, r)
		return r
	case UserInfoRes:
		u := new(ResUserInfoMessage)
		gconv.Struct(msg.Data, u)
		fmt.Println("u是?", u)
		return u
	case ChatRes:
		l := new(ResChatMessage)

		gconv.Struct(msg.Data, l)
		log.Println("ChatMessage解包", l)
		return l
	}
	return nil
}
